#! /usr/bin/env python
#coding=utf-8
import urllib,urllib2,random,time
import tornado.web

def runpoll(who,num):
    url = "http://su.100steps.net/2007/vote/vote.php";
    post_data = urllib.urlencode({"tid":91,"vid":who,"submit":"给我投上宝贵一票吧"})
    start = time.time()
    for i in range(num):
        headers = {'X-Forwarded-For': "125.217."+str(random.randint(1,255))+"."+str(random.randint(1,255))}
        req = urllib2.Request(url, post_data, headers)
        response = urllib2.urlopen(req)
        result = unicode(response.read(),'gbk')
        result = "成功" if u"成功" in result else "失败"
        print i+1,result
    usetime = time.time() - start
    return "共投了: " + str(i+1) + "票 . 用时 : " + str(usetime) + "秒 ."

def check():
    gap = 277
    who = 2562
    url = "http://su.100steps.net/2007/vote/result.php?tid=91"
    page = unicode(urllib2.urlopen(url).read(),'gbk').split('\n')
    #print page
    listid = map(lambda line:int(line[45:49]),page[16:35:2])
    listnum = map(lambda line:int(line[-15:-9].split('[')[1]),page[17:36:2])
    list = {}
    for (id,num) in zip(listid,listnum):
        list[id] = num
    #print listid[0],list[who],listnum[1]
    if(listid[0]!=who or (list[who]-listnum[1])<gap):
        num = listnum[0] + gap - list[who] if listid[0]!=who else listnum[1] + gap - list[who]
        return runpoll(who,num)
    else: return "wait"
    #print list

class BaseHandler(tornado.web.RequestHandler):
    def prepare(self):
        pass
        
class view(BaseHandler):
    def get(self):
        self.render("index.html")

class poll(BaseHandler):           
    def get(self):
        mess = check()
        self.render("poll.html",mess=mess)

if __name__ == "__main__":
    check()
